export function IRKlan(html) {
    const result = { ...html };
    let hasAdSlot = false;

    const slotDefinitionsPerPage = {
        hd_index: '',
        hd_details: '',
        hd_category: '',
        hd_play: ''
    };

    for (const key in result) {
        if (key.startsWith("ad") && result[key]) {
            const value = result[key].trim();
            const id = getIDs(value);
            const match = key.match(/^ad(\d)_\d+$/);

            if (id && match) {
                const pageIndex = parseInt(match[1], 10);
                const pageKey = ["hd_index", "hd_details", "hd_category", "hd_play"][pageIndex];
                slotDefinitionsPerPage[pageKey] += value + "\n";
                result[key] = getEachslot(id, key);
                hasAdSlot = true;
            } else {
                result[key] = "";
            }
        }
    }

    let gptScript = '';
    if (result.htmlTest !== null) {
        gptScript += `${result.htmlTest}\n`;
    }
    if (result.fpcode !== null) {
        gptScript += generateFpCodeScript(result.fpcode)
    }
    if (hasAdSlot) {
        gptScript += `<script async src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>\n`;
    }

    for (const key in slotDefinitionsPerPage) {
        const defs = slotDefinitionsPerPage[key].trim();
        if (defs) {
            result[key] = buildHeaderSlot(defs);
        }
    }

    const interstitial = result.interstitial?.trim() || '';
    const anchor = result.anchor?.trim() || '';
    if (interstitial || anchor) {
        gptScript += buildInterAchor(interstitial, anchor);
    }

    result.htmlTest = gptScript.trim();
    return result;
}


export function generateFpCodeScript(fpcode) {
    if (!fpcode || !fpcode.clientid || !fpcode.platformid || !fpcode.tagid) {
        return '';
    }

    return `<!-- ----HEAD---- gpt.js to be also placed only once per page -->
  <script async src='https://p.adlooxtracking.com/gpt/a.js'></script>
  <script>
      window.adloox_pubint = window.adloox_pubint || {cmd: []};
      adloox_pubint.cmd.push(function () {
          adloox_pubint.init({
              clientid: ${fpcode.clientid}, platformid: ${fpcode.platformid}, tagid: ${fpcode.tagid}
          });
      });
      window.googletag = window.googletag || {cmd: []};
      googletag.cmd.push(function () {
          adloox_pubint.cmd.push(function () {
              adloox_pubint.gpt_js(googletag);
          });
      });
      var adloox_pubint_timeout = function (fn, to) {
          var cb = (function (that) {
              return function () {
                  if (!cb.t)
                      return;
                  window.clearTimeout(cb.t);
                  delete cb.t;
                  fn.apply(that);
              };
          })(this);
          cb.t = window.setTimeout(cb, to);
          return cb;
      };
  </script>
  `;
}


// 填充广告位处理
function getIDs(adSlot) {
    const regex = /'([^']+)'\).addService\(googletag\.pubads\(\)\);/;
    const matches = adSlot.match(regex);
    return matches ? matches[1] : null;
}

function getEachslot(id, key, service = "adloox_pubint") {
    if (!id) return "";

    const isIndexZero = /^ad\d+_0$/.test(key);
    const dataAttr = isIndexZero ? ' data-ad-index="0"' : "";

    return `
    <div class="ad-container"${dataAttr}>
      <!--${id}-->
      <div class='gptslot' id='${id}'>
        <script>
          googletag.cmd.push(function () {
            var cb = ${service}_timeout(function () {
              googletag.display('${id}');
            }, 700);
            ${service}.cmd.push(function () {
              ${service}.gpt(googletag, cb);
            });
          });
        </script>
      </div>
    </div>`;
}

function buildInterAchor(inter, anchor) {
    if (inter === '' && anchor === '') { return ''; }
    let script = ``;
    script = `\n<script>
    window.googletag = window.googletag || { cmd: [] };
    googletag.cmd.push(function () {`
    if (inter) {
        script += ` // Define interstitial ad slot
    var interstitialSlot = googletag.defineOutOfPageSlot('${inter}', googletag.enums.OutOfPageFormat.INTERSTITIAL);
     if (interstitialSlot) {
        interstitialSlot.addService(googletag.pubads()).setConfig({
            interstitial: {
                triggers: {
                    navBar: true,
                    unhideWindow: true,
                },
            },
        });
    }
    googletag.pubads().enableSingleRequest();
    googletag.enableServices();

    var cb = adloox_pubint_timeout(function () {
        googletag.display(interstitialSlot);
    }, 700); // 700 milliseconds maximum delay
    adloox_pubint.cmd.push(function () {
        adloox_pubint.gpt(googletag, cb);
    });`
    }
    if (anchor) {
        script += `  
    var anchorSlot = googletag.defineOutOfPageSlot('${anchor}', googletag.enums.OutOfPageFormat.BOTTOM_ANCHOR);
       if (anchorSlot) {
        anchorSlot.setTargeting('test', 'anchor').addService(googletag.pubads());
    }
    googletag.pubads().enableSingleRequest();
    googletag.enableServices();

    var cb = adloox_pubint_timeout(function () {
        googletag.display(anchorSlot);
    }, 700); // 700 milliseconds maximum delay
    adloox_pubint.cmd.push(function () {
        adloox_pubint.gpt(googletag, cb);
    });`;
    }
    script += `});
  </script>`;

    return script;

}
function buildHeaderSlot(tempHtml) {
    if (!tempHtml.trim()) return '';
    return `<script>
    window.googletag = window.googletag || { cmd: [] };
    googletag.cmd.push(function () {
${tempHtml}
        googletag.pubads().enableSingleRequest();
        googletag.enableServices();
    });
</script>`;
}


IRKlan.exampleForm = {
    host: 'www.irklan.com',
    dirpath: 'example',
    html: {
        htmlTest: ``,
        hd_index: ``,
        hd_details: ``,
        hd_category: ``,
        hd_play: ``,
        ad0_0: `googletag.defineSlot('/23200510714,23189498746/8289455-BANNER-1',[[300,250],'fluid'], 'rtbbanner1').addService(googletag.pubads());`,
        ad0_1: `googletag.defineSlot('/23200510714,23189498746/8289455-BANNER-2',[[300,250],'fluid'], 'rtbbanner2').addService(googletag.pubads());`,
        ad0_2: `googletag.defineSlot('/23200510714,23189498746/8289455-BANNER-3',[[300,250],'fluid'], 'rtbbanner3').addService(googletag.pubads());`,
        ad0_3: `googletag.defineSlot('/23200510714,23189498746/8289455-BANNER-4',[[300,250],'fluid'], 'rtbbanner4').addService(googletag.pubads());`,
        ad0_4: `googletag.defineSlot('/23200510714,23189498746/8289455-BANNER-5',[[300,250],'fluid'], 'rtbbanner5').addService(googletag.pubads());`,
        ad1_0: `googletag.defineSlot('/23200510714,23189498746/8289455-BANNER-6',[[300,250],'fluid'], 'rtbbanner6').addService(googletag.pubads());`,
        ad1_1: ``,
        ad1_2: ``,
        interstitial: `/23200510714,23189498746/8289455-INTER-1`,
        anchor: `/23200510714,23189498746/8289455-ANCHOR-1`,
    }
}

export function parseIRklanCode(rawInputString) {
    const obj = {
        type: 'irklan',
        items: {},
    };

    obj.items.fpcode = getFpCodeID(rawInputString)

    let inputString = rawInputString.split('\n').filter(line => line.length > 0).join(' ');
    const lines = (inputString.match(/[^;]+;/g) || []).filter(line => /define(?:OutOfPageSlot|Slot)\(/i.test(line));

    let commands = [];
    let paths = [];
    const slotRegex = /googletag\.define(?:OutOfPageSlot|Slot)\(([^)]+)\)/i;
    lines.forEach(line => {
        const match = line.match(slotRegex);
        if (match) {
            const Path_Match0 = match[0];
            const lowerPath = Path_Match0.toLowerCase();
            if (Path_Match0.includes('defineOutOfPageSlot') || lowerPath.includes('-inter-') || lowerPath.includes('-anchor-')) {
                const pathMatch = Path_Match0.match(/'([^']+)'/);
                if (pathMatch && pathMatch[1]) {
                    const path = pathMatch[1];
                    if (!paths.includes(path)) {
                        paths.push(path);
                    }
                }
            } else {
                commands.push(`${Path_Match0}.addService(googletag.pubads());`);
            }
        }
    });

    getInterAnchorKey(obj.items, paths)
    assignAdKeys(obj.items, commands)
    return obj;
}

function getFpCodeID(htmlString) {
    const fpMatch = htmlString.match(/clientid\s*:\s*(\d+)[^}]*?platformid\s*:\s*(\d+)[^}]*?tagid\s*:\s*(\d+)/i);
    if (fpMatch) {
        return {
            clientid: fpMatch[1],
            platformid: fpMatch[2],
            tagid: fpMatch[3]
        };
    }

    return null;
}


function getInterAnchorKey(items, paths) {
    let fallback = [];

    for (let i = 0; i < paths.length; i++) {
        const path = paths[i];
        const lower = path.toLowerCase();

        if (lower.includes('inter') && !items.interstitial) {
            items.interstitial = path;
        } else if (lower.includes('anchor') && !items.anchor) {
            items.anchor = path;
        } else {
            fallback.push(path);
        }
    }

    if (!items.interstitial && fallback[0]) {
        items.interstitial = fallback[0];
    }
    if (!items.anchor && fallback[1]) {
        items.anchor = fallback[1];
    }
}

function assignAdKeys(items, commands) {
    let indexMap = { ad0: 0, ad1: 0, ad2: 0 };

    commands.forEach((cmd, i) => {
        if (indexMap.ad0 < 4) {
            const key = `ad0_${indexMap.ad0++}`;
            items[key] = cmd;
        } else if (indexMap.ad1 < 2) {
            const key = `ad1_${indexMap.ad1++}`;
            items[key] = cmd;
        } else if (indexMap.ad2 < 2) {
            // const key = `ad2_${indexMap.ad2++}`;
            // items[key] = cmd;
        }
    });
}


